from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib
from data.api.env import MAIL_ENV
# def send_email(host, port, sender, code, receivers, subject, content, attachment_path):

def send_email(host=MAIL_ENV["邮件服务商主机"], port=MAIL_ENV["邮件服务商端口号"], sender=MAIL_ENV["发件人邮箱"], code=MAIL_ENV["授权码"],
                   receivers=MAIL_ENV["收件人列表"], subject=MAIL_ENV["邮件标题"], content=MAIL_ENV["邮件正文"], attachment_path=MAIL_ENV["附件目录"]):
    # 创建邮件
    mail = MIMEMultipart()
    mail['From'] = sender
    mail['To'] = ', '.join(receivers) # 这只是为了显示，实际发送时不需要
    mail['Subject'] = subject
     # 添加附件
    with open(attachment_path, 'r', encoding='utf-8') as file:
        report = file.read()
    attachment = MIMEText(report, 'html', 'utf-8') # 如果附件是 HTML，则使用 'html'
    attachment['Content-Disposition'] = f'attachment; filename="{attachment_path.split("/")[-1]}"'
    mail.attach(attachment)
     # 添加正文
    body = MIMEText(content, "html", "utf-8")
    mail.attach(body)
     # 发送邮件
    try:
        smtp = smtplib.SMTP_SSL(host, port) # 使用 SMTP_SSL 类进行 SSL 连接
        smtp.login(sender, code)
        smtp.sendmail(sender, receivers, mail.as_string())
        smtp.quit() # 使用 quit() 而不是 close()，但 close() 通常也可以
        print("邮件发送完毕")
    except Exception as e:
        # raise e
        print(f"邮件发送失败: {e}")
 # 使用示例
if __name__ == "__main__":
    # # 邮箱设置
    # host = 'smtp.qq.com'
    # port = 465 # 使用 SSL 连接
    # sender = "1098280716@qq.com"
    # code = "gypulmvqcoxjhija" # 确保这是正确的授权码
    # receivers = ["1098280716@qq.com"] # 直接使用列表
    #  # 邮件内容
    # subject = "测试报告"
    # content = """
    # <p>Dear 经理:</p >
    # <br>
    # <p>自动化测试报告第一期已经完成，请查收</p ><br>
    # <p>此致</p >
    # <p>敬礼</p >
    # <p>张三</p >
    # """
    # attachment_path = 'test.html'
    #  # 发送邮件
    # send_email(host, port, sender, code, receivers, subject, content, attachment_path)
    send_email()